//
//  ZJZXContentViewController.m
//  Rong360
//
//  Created by tianliwei on 1/3/14.
//  Copyright (c) 2014 tianliwei. All rights reserved.
//

#import "ZJZXContentViewController.h"
#import "CityListViewController.h"
#import "DetailMessageViewController.h"
#import "HPGrowingTextView.h"
#import "MessageCell.h"
#import "MsgInfo.h"
#import "NetCheckUtil.h"
#import "APService.h"
@interface ZJZXContentViewController ()<HPGrowingTextViewDelegate>
@property (strong, nonatomic) NSArray *messageArray;
@property (strong, nonatomic) NSArray *replyMessages;
@property (strong, nonatomic) HPGrowingTextView *textView;
@property (strong, nonatomic) UIView *containerView;
@property (strong, nonatomic) UIButton *doneBtn;
@end

static NSString *cellIdentifier = @"MessageCell";

@implementation ZJZXContentViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(keyboardWillShow:)
													 name:UIKeyboardWillShowNotification
												   object:nil];
		[[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(keyboardWillHide:)
													 name:UIKeyboardWillHideNotification
												   object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDataBase:) name:kAskQuestionSuccess object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(reloadGridView)
													 name:kNewMsgNotification
												   object:nil];
	}
    return self;
}

- (void)reloadGridView{
    [self.tableView reloadData];
}

- (void)updateDataBase:(NSNotification*)notification{
    NSDictionary *dic = notification.userInfo;
    NSString *currentTime = [[ToolOperation shareTool] stringOfCurrentDateTool2];
    MsgInfo *msgInfo = [[MsgInfo alloc]initWithQuesID:[dic objectForKey:@"QuesID"] quesStr:[NSString stringWithFormat:@"问:%@",self.textView.text] reply:@"待回答。" time:currentTime bRead:0 bReply:0];
    [[DBMan shareDB] saveToQA:msgInfo];
    self.messageArray = [[DBMan shareDB] getAllSectionQuesIDInQAInfo];
    
    if (self.messageArray.count == 0) {
        self.tipLabel.hidden = NO;
    }else{
        self.tipLabel.hidden = YES;
    }
    
    if (self.messageArray.count > 0) {
        //就剩这个问题了
        [self.tableView reloadData];

        self.tableView.contentOffset = CGPointMake(0, self.tableView.contentSize.height-(self.tableView.height - 252));
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 252, 0);
//        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.messageArray.count-1 inSection:0];
//        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
    
    //清空字符串
    self.textView.text = @"";
}

- (void) citySelectionUpdate:(NSString*)selectedCity selectedCityID:(NSString *)selectedCityID{
//    [[NSUserDefaults standardUserDefaults]setObject:selectedCityID forKey:kCurrentCityID];
//    [[NSUserDefaults standardUserDefaults]setObject:selectedCity forKey:kCurrentCity];
    
    NSString *productPara = [NSString stringWithFormat:@"city_id=%@",selectedCityID];
    NSString *productUrl = [NSString stringWithFormat:@"%@?%@&token=%@",ProductUrl,productPara,[SignUtil stringFromURL:productPara]];
    NSLog(@"productUrl:======> %@\n",productUrl);
    [RequestUtil requestWithType:Product Url:productUrl];
    UIButton *button = (UIButton *)self.navigationItem.rightBarButtonItem.customView;
    [button setTitle:selectedCity forState:UIControlStateNormal];
//    [APService setTags:[NSSet setWithObject:selectedCity] callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:self];
    [[NSNotificationCenter defaultCenter]postNotificationName:kUpdateCityNotification object:nil userInfo:nil];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"专家咨询";
    self.messageArray = [[DBMan shareDB] getAllSectionQuesIDInQAInfo];
    if (!self.messageArray) {
        self.messageArray = [NSArray array];
    }
    if (self.messageArray.count == 0) {
        self.tipLabel.hidden = NO;
    }else{
        self.tipLabel.hidden = YES;
    }
    NSString *currentCity = [[NSUserDefaults standardUserDefaults]objectForKey:kCurrentCity];
    UIButton *cityButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [cityButton setBackgroundColor:[UIColor clearColor]];
    [cityButton setTitle:currentCity forState:UIControlStateNormal];
    [cityButton addTarget:self action:@selector(presentCityViewController) forControlEvents:UIControlEventTouchUpInside];
    cityButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    cityButton.frame = CGRectMake(0.0f, 0.0f, 80.0f, 25.0f);
    UIBarButtonItem *cityButtonItem = [[UIBarButtonItem alloc] initWithCustomView:cityButton];
    self.navigationItem.rightBarButtonItem = cityButtonItem;
    
	self.containerView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 40, 320, 40)];
    self.containerView.backgroundColor = RGBCOLOR(240, 240, 240);
	self.textView = [[HPGrowingTextView alloc] initWithFrame:CGRectMake(20, 0, 230, 40)];
    self.textView.isScrollable = NO;
    self.textView.contentInset = UIEdgeInsetsMake(0, 5, 0, 5);
    
	self.textView.minNumberOfLines = 1;
	self.textView.maxNumberOfLines = 6;
    // you can also set the maximum height in points with maxHeight
    // textView.maxHeight = 200.0f;
	self.textView.returnKeyType = UIReturnKeyGo; //just as an example
	self.textView.font = [UIFont systemFontOfSize:18.0f];
	self.textView.delegate = self;
    self.textView.internalTextView.scrollIndicatorInsets = UIEdgeInsetsMake(5, 0, 5, 0);
    self.textView.backgroundColor = [UIColor clearColor];
    self.textView.textColor = [UIColor blackColor];
    self.textView.placeholder = @"您的提问";
	// textView.animateHeightChange = NO; //turns off animation
    
    [self.view addSubview:self.containerView];
	
    UIImageView *tvImageView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"tf_ques"]stretchableImageWithLeftCapWidth:20 topCapHeight:20]];
    tvImageView.frame = CGRectMake(10, 0, 250, 40);
    tvImageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    // view hierachy
    [self.containerView addSubview:tvImageView];
    [self.containerView addSubview:self.textView];
    
    if ([NetCheckUtil isNetworkRunning]) {
        self.doneBtn = [UIButton buttonWithTag:0 frame:CGRectMake(self.containerView.frame.size.width - 65, 5, 60, 30) title:@"提问" fontSize:20 color:APPCOLOR target:self action:@selector(sendText)];
    }else{
        self.doneBtn = [UIButton buttonWithTag:0 frame:CGRectMake(self.containerView.frame.size.width - 65, 5, 60, 30) title:@"提问" fontSize:20 color:[UIColor lightGrayColor] target:self action:@selector(sendText)];
    }
	
    self.doneBtn.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
	[self.containerView addSubview:self.doneBtn];
    
    self.containerView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"MessageCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView reloadData];
    if (self.tableView.contentSize.height > self.tableView.frame.size.height) {
        self.tableView.contentOffset = CGPointMake(0, self.tableView.contentSize.height-self.tableView.frame.size.height);
    }
    
}

-(void)resignTextView
{
	[self.textView resignFirstResponder];
}

//Code from Brett Schumann
-(void) keyboardWillShow:(NSNotification *)note{
    // get keyboard size and loctaion
    
	CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    // Need to translate the bounds to account for rotation.
    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
    
	// get a rect for the textView frame
	CGRect containerFrame = self.containerView.frame;
    containerFrame.origin.y = self.view.bounds.size.height - (keyboardBounds.size.height + containerFrame.size.height);
    
	// animations settings
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
	
	// set views with new info
	self.containerView.frame = containerFrame;
    if (self.tableView.contentSize.height>(self.tableView.frame.size.height-keyboardBounds.size.height)) {
        self.tableView.contentOffset = CGPointMake(0, self.tableView.contentSize.height-(self.tableView.frame.size.height-keyboardBounds.size.height));
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 252, 0);
    }
    
    
	// commit animations
	[UIView commitAnimations];
    

}

-(void) keyboardWillHide:(NSNotification *)note{
    
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
	
	// get a rect for the textView frame
	CGRect containerFrame = self.containerView.frame;
    containerFrame.origin.y = self.view.bounds.size.height - containerFrame.size.height;
	
	// animations settings
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
	// set views with new info
	self.containerView.frame = containerFrame;
	
	// commit animations
	[UIView commitAnimations];
    
}

- (void)growingTextView:(HPGrowingTextView *)growingTextView willChangeHeight:(float)height
{
    float diff = (growingTextView.frame.size.height - height);
    
	CGRect r = self.containerView.frame;
    r.size.height -= diff;
    r.origin.y += diff;
	self.containerView.frame = r;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *quesID = self.messageArray[indexPath.section];
    self.replyMessages = [[DBMan shareDB]getAllReplysByQuestionID:quesID];
    if (!self.replyMessages) {
        self.replyMessages = [NSArray array];
    }
    MsgInfo *msgInfo = self.replyMessages[indexPath.row];
    if (msgInfo) {
        CGSize size = [msgInfo.quesStr sizeWithFont:[UIFont systemFontOfSize:18.0] constrainedToSize:CGSizeMake(280, 9999) lineBreakMode:NSLineBreakByCharWrapping];
        return size.height+70;
    }
    return 0;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.messageArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.hidesBottomBarWhenPushed = YES;
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *quesID = self.messageArray[indexPath.section];
    NSLog(@"==>QuesID: %@\n",quesID);
    [[DBMan shareDB]updateReadFlagbyID:quesID];
    self.replyMessages = [[DBMan shareDB] getAllReplysByQuestionID:quesID];
    MsgInfo *msgInfo = self.replyMessages[indexPath.row];
    DetailMessageViewController *detailMsgVC = [[DetailMessageViewController alloc]initWithQues:msgInfo.quesStr replies:self.replyMessages];
    [self.navigationController pushViewController:detailMsgVC animated:YES];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MessageCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    [cell.backImgView setImage:[[UIImage imageNamed:@"tf_ques"]stretchableImageWithLeftCapWidth:10 topCapHeight:10]];
    NSString *quesID = self.messageArray[indexPath.section];
    NSLog(@"==>QuesID: %@\n",quesID);
    self.replyMessages = [[DBMan shareDB] getAllReplysByQuestionID:quesID];
    MsgInfo *msgInfo = self.replyMessages[0];
    
    cell.quesLabel.text = msgInfo.quesStr;
    cell.quesLabel.numberOfLines = 0;
    [cell.quesLabel resizeToFit];
    cell.ansLabel.text = msgInfo.reply;
    cell.timeLabel.text = msgInfo.time;
    
    
    if ([self checkIndicatorWithReplies:self.replyMessages]==YES) {
        cell.indicatorImg.hidden = NO;
    }else{
        cell.indicatorImg.hidden = YES;
    }
    
    return cell;
}

- (BOOL)checkIndicatorWithReplies:(NSArray *)replies{
    for (int i = 0; i < replies.count; i++) {
        MsgInfo *msgInfo = replies[i];
        if (msgInfo.isReply == 1 && msgInfo.isRead == 0) {
            return YES;
        }
    }
    return NO;
}

#pragma mark - Messages view delegate
- (void)sendText
{
    if ([NetCheckUtil isNetworkRunning]) {
        if (self.textView.text.length > 0) {
            NSString *mailStr = [[NSUserDefaults standardUserDefaults]objectForKey:kUserMailBox];
            if (mailStr) {
                NSString *askPara = [NSString stringWithFormat:@"city_id=%@&question=%@&user_email=%@&user_rid=%@",[[NSUserDefaults standardUserDefaults]objectForKey:kCurrentCityID],self.textView.text,mailStr,[[NSUserDefaults standardUserDefaults]objectForKey:kOpenUdid]];
                NSString *askUrl = [NSString stringWithFormat:@"%@?%@&token=%@",AskUrl,askPara,[SignUtil stringFromURL:askPara]];
                NSLog(@"askUrl:======> %@\n",askUrl);
                [RequestUtil requestWithType:Question Url:askUrl];
            }else{
                NSString *askPara = [NSString stringWithFormat:@"city_id=%@&question=%@&user_rid=%@",[[NSUserDefaults standardUserDefaults]objectForKey:kCurrentCityID],self.textView.text,[[NSUserDefaults standardUserDefaults]objectForKey:kOpenUdid]];
                NSString *askUrl = [NSString stringWithFormat:@"%@?%@&token=%@",AskUrl,askPara,[SignUtil stringFromURL:askPara]];
                NSLog(@"askUrl:======> %@\n",askUrl);
                [RequestUtil requestWithType:Question Url:askUrl];
            }
            
        }else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请您先输入问题再进行提问哦" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        }
    }else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"当前没有网络，请先确保网络正常再进行提问哦" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
    
}


- (void)presentCityViewController{
    CityListViewController *cityVC = [[CityListViewController alloc]init];
    cityVC.delegate = self;
    UINavigationController *naviVC = [[UINavigationController alloc]initWithRootViewController:cityVC];
    [self presentModalViewController:naviVC animated:YES];
}

//- (void)tagsAliasCallback:(int)iResCode tags:(NSSet*)tags alias:(NSString*)alias {
//    NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, tags , alias);
//}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
